package com.example.wangning.mycarofcountry.recommend.vehicle;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.mycarofcountry.entity.dao.Recommend_Vehiclelist;
import com.example.wangning.mycarofcountry.R;
import com.example.wangning.mycarofcountry.cache.VolleySingleton;
import com.example.wangning.mycarofcountry.db.DaoHelper;
import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dllo on 16/1/6.
 */
public class VehicleFragment extends Fragment {
    private ListView listView;
    private VehicleAdapter vehicleAdapter;
    private VolleySingleton queue;
    private SwipeRefreshLayout news_Swipe;
    private TextView news_Tv;
    private DaoHelper helper;
    private String url = "http://223.99.255.20/app.api.autohome.com.cn/autov5.3.0/news/fastnewslist-pm2-b0-l0-s20-lastid0.json";

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_vehicle, null);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        listView = (ListView) view.findViewById(R.id.listview);
        news_Swipe = (SwipeRefreshLayout) view.findViewById(R.id.news_Swipe);
        news_Tv = (TextView) view.findViewById(R.id.news_Tv);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        vehicleAdapter = new VehicleAdapter(getActivity());
        listView.setAdapter(vehicleAdapter);
        helper = DaoHelper.getInstance();
        initData(url);
        setrefresh();
    }

    private void setrefresh() {
        //设置刷新时动画的颜色，可以设置4个
        news_Swipe.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
        news_Swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                news_Tv.setVisibility(View.VISIBLE);
                news_Tv.setText("正在刷新");
                initData(url);
            }
        });


    }

    private void initData(String url) {
        queue = VolleySingleton.getVolleyIntance();

        StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                VehicleBean vehicleBean = gson.fromJson(response, VehicleBean.class);
                if (vehicleBean != null) {
                    VehicleResult vehicleResult = vehicleBean.getResult();
                    List<Recommend_Vehiclelist> vehiclelists = vehicleResult.getList();
                    if (vehiclelists != null && vehiclelists.size() > 0) {
                        vehicleAdapter.addData(vehiclelists);
                        helper.addVehiclelist(vehiclelists);
                        new Handler().postDelayed(new Runnable() {

                            @Override
                            public void run() {
                                news_Tv.setText("");
                                news_Tv.setVisibility(View.GONE);
                            }
                        }, 1000);
                        news_Swipe.setRefreshing(false);
                    }
                }
            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                vehicleAdapter.addData(helper.searchVehiclelist());
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                try {
                    String jsonString = new String(response.data, "UTF-8");
                    return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                } catch (Exception je) {
                    return Response.error(new ParseError(je));
                }
            }
        };
        queue.addRequest(stringRequest);
    }

}

